﻿//创建人：longb
//日期：2022-04-25
//描述：日历维护HTML页面
var page = {
    pagetotal: 0,
    pageSize: 20,
    pageNumber: 1,
    pagetotalp: 0,
    pageSizep: 20,
    pageNumberp: 1,
    rootPath: getRootPath(), //网站根路径
    ajaxUrl: getRootPath() + "/Ashx/ApsHandler/MakeCalendarHandler.ashx",
    MainCaData: null,
    CaData: null,
    message: '',
    Year: new Date().getFullYear(),
    //初始化页面
    init: function () {
        page.bind();
        page.GetMainCaData();
    },
    //页面事件绑定
    bind: function () {
        for (var i = 1; i <= 12; i++) {
            $('#LYcalendar' + i).calendar({ year: page.Year, month: i });

            $('#LYcalendar' + i).calendar({
                onSelect: function (date) {
                    var MAKECALENDARID = $('#MAKECALENDARID').val();
                    var starteDate = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
                    if (MAKECALENDARID == "") { displayMessage("请先选择日历模板"); return; }
                    $("#popStartDate").textbox('setValue', starteDate);
                    $("#hdMakeCalendarID").val(MAKECALENDARID);
                    $('#dd').dialog({
                        title: '假期维护',
                        width: 400,
                        height: 250,
                        closed: false,
                        cache: false,
                        modal: true,
                        onOpen: function () {
                            page.message = '';
                            clearMessage();
                            page.GetDetailCaData(starteDate);
                        },
                        buttons: [{ text: '保存',
                            handler: function () { page.SaveOrUpdateDetaileCaData(); }
                        }, { text: '删除',
                            handler: function () { page.DeleteDetailCaData(); }
                        }]
                    });
                },
                onNavigate: function (year, data) {
                    if (new Date().getMonth() + 1 != i) {
                        $('#LYcalendar' + i).find('.calendar-day').removeClass('calendar-selected');
                    }
                    $('#LYcalendar' + i).find('.calendar-nav').removeClass('calendar-prevyear calendar-nextyear calendar-prevmonth calendar-nextmonth');
                },
                formatter: function (date) {
                    var y = date.getYear();
                    var m = date.getMonth() + 1;
                    var d = date.getDate();
                    var opts = $(this).calendar('options');

                    return page.CalendarFormatter(y, m, d);
                }
            });
        }
    },
    //格式化日历，每天的样式
    CalendarFormatter: function (y, m, d) {
        var str = '<div style="">' + d + '</div>';
        $.each(page.CaData, function (index, item) {
            var dat = new Date(item.HOLIDAYDATE);
            if (navigator.userAgent.indexOf("MSIE") > -1) { dat = new Date(item.HOLIDAYDATE.replace(/-/g, '/')); }
            if (dat.getYear() == y && (dat.getMonth() + 1) == m && dat.getDate() == d) {
                str = '<div style="background-color:#D6F1FF;">' + d + '</div>';
                return str;
            }
        });
        return str;
    },
    QueryCaData: function () {
        page.message = '';
        clearMessage();
        page.GetDetailCaData('')
    },
    //获取主表数据
    GetMainCaData: function () {
       $(function () { 
        $('#MAKECALENDARIDD').combo({required:true,editable:false,panelWidth: 0,panelHeight: 0,onShowPanel:function(){
            $('#sp').dialog({
            title: '',
            width: 600,
            height: 350,
            closed: false,
            cache: false,
            modal: true
        }); page.LoadMainCaData();
        }});
         $('#selMakeCalendar').datagrid({
            toolbar:'#tb',
            singleSelect:true,
            columns: [[
                    { field: 'MAKEYEAR', title: '年份', width: 70, align: 'center'},
                    { field: 'MAKECALENDARNAME', title: '日历名称', width: 100, align: 'center'},
                    { field: 'DESCRIPTION', title: '描述', width: 100, align: 'center'},
                    { field: 'ISUSE', title: '是否启用', width: 60, align: 'center',formatter:function(value,row,index){if(value==0){return '是';}else{return '否';}}},
                    { field: 'FULLNAME', title: '创建人', width: 70, align: 'center'},
                    { field: 'CREATEDATE', title: '创建时间', width: 150, align: 'center'}
                    ]],
           onSelect:function(index,row){
                    $('#MAKECALENDARIDD').combo('setText',row.MAKECALENDARNAME);
                    $('#calendarForm').form('load', row);
                    $('#MAKEYEAR').textbox('readonly', true);
                    $('.validatebox-readonly').css('background-color', '#ccc');
                    page.Year = row.MAKEYEAR;
                    clearMessage();
                    page.message = '';
                    page.GetDetailCaData('');
                    $('#sp').dialog('close');
           }
        });
        });
    },
    LoadMainCaData:function(){
        $('#selMakeCalendar').datagrid('loadData', []);
        var formData = { action: "GetMainCaData",MAKEYEAR:$('#MAKEYEARR').numberbox('getValue'),MAKECALENDARNAME:$('#MAKECALENDARNAMEE').textbox('getValue')};
        page.post(formData, function (res) {
            page.MainCaData = res.DBTable;
            if (res.Result) {
            $('#selMakeCalendar').datagrid('loadData', res.DBTable);
            }});
    },
    ResetSearch:function(){
        $('#selMakeCalendar').datagrid('loadData', []);
        $('#MAKEYEARR').numberbox('setValue','');
        $('#MAKECALENDARNAMEE').textbox('setValue','')
    },
    //获取对应年月日历信息
    GetDetailCaData: function (date) {
        page.CaData = null;
        var formData = { action: "GetDetailCaData", MID: $('#MAKECALENDARID').val(), Date: date };
        page.post(formData, function (res) {
            clearMessage();
            if (res.Result) {
                if (date != "") {
                    var ffData = { "holidayName": '', "MakeCalendarDetailID": '' };
                    if (res.DBTable.length > 0) {
                        ffData = { "holidayName": res.DBTable[0].HOLIDAYNAME, "MakeCalendarDetailID": res.DBTable[0].MAKECALENDARDETAILID };
                    }
                    $('#ff').form('load', ffData);
                } else {
                    page.CaData = res.DBTable;

                }
            }
            if (date == "") { page.bind(); }
            if (page.message != "" || $('#MAKECALENDARID').val() == "") { displayMessage(page.message, true); }
            else if (!res.Result) displayMessage(res.Message, res.Result);

        });
    },
    //新建日历主表信息
    CreateMainCaData: function () {
        $('#calendarForm').form('clear');
        $('#ISUSE').combobox('setValue', '0');
        $('#MAKEYEAR').textbox('readonly', false);
        $('#MAKECALENDARIDD').combo('setText', '');
        $('.textbox-text').css('background-color', '#fff');
        page.CaData = null;
        page.bind();
        clearMessage();
    },
    //保存日历主表信息
    SaveOrUpdateMainCaData: function () {
        if ($('#MAKECALENDARNAME').val() == "") {
            displayMessage('请输入日历名称');
            return;
        }
        var data = {};
        var frdata = $('#calendarForm').serializeArray();
        $.each(frdata, function () {
            data[this.name] = this.value
        });
        var formData = { action: "SaveOrUpdateMainCaData", CaData: JSON.stringify([data]) };
        page.post(formData, function (res) {
            if (res.Result) {
                page.LoadMainCaData();
                $('#MAKECALENDARIDD').combo('setText', data.MAKECALENDARNAME);
                page.Year=data.MAKEYEAR;
                page.bind();
            }
            $('#MAKECALENDARID').val(res.ReturnData);
            page.message = res.Message;
            displayMessage(res.Message, res.Result);
        });
    },
    //删除日历主表信息
    DaleteMainCaData: function () {
        $.messager.confirm('确认', '假期明细也会删除，确定要删除吗？', function (flag) {
            if (flag) {
                var formData = { action: "DaleteMainCaData", MID: $('#MAKECALENDARID').val() };
                page.post(formData, function (res) {
                    if (res.Result) {
                        page.CaData = null;
                        page.CreateMainCaData();
                        page.LoadMainCaData();
                    }
                    displayMessage(res.Message, res.Result);
                });
            }
        });

    },
    //保存日历天安排信息
    SaveOrUpdateDetaileCaData: function () {
        page.message = '';
        var data = {};
        var formData = $('#ff').serializeArray();
        $.each(formData, function () {
            data[this.name] = this.value
        });
        var formData = { action: "SaveOrUpdateDetaileCaData", DetaileCaData: JSON.stringify([data]) };
        page.post(formData, function (res) {
            if (res.Result) {
                $('#dd').dialog("close");
                page.GetDetailCaData('');
            }
            page.message = res.Message;
            //            displayMessage(res.Message, res.Result);
        });
    },
    //删除日历日假期
    DeleteDetailCaData: function () {
        page.message = '';
        var data = {};
        var formData = $('#ff').serializeArray();
        $.each(formData, function () {
            data[this.name] = this.value
        });
        var formData = { action: "DeleteDetailCaData", DetaileCaData: JSON.stringify([data]) };
        page.post(formData, function (res) {
            if (res.Result) {
                $('#dd').dialog("close");
                page.GetDetailCaData('');
            }
            page.message = res.Message;
            //            displayMessage(res.Message, res.Result);
        });
    },
    //周六，周日批量设定
    BatchHolidaySet: function (type) {
        page.message = '';
        var MID = $('#MAKECALENDARID').val();
        if (MID == "") { displayMessage("请先选择日历模板"); return; }
        //        var Year = new Date().getFullYear();
        var formData = { action: "BatchHolidaySet", MID: MID, Year: page.Year, Type: type };
        page.post(formData, function (res) {
            if (res.Result) {
                page.GetDetailCaData('');
            }
            page.message = res.Message;
            //displayMessage(res.Message, res.Result);
        });
    },
    ///日历关系设置
    BindRelationSet: function () {
        var MID = $('#MAKECALENDARID').val();
        if (MID == "") { displayMessage("请先选择日历模板"); return; }
        var Calendar = $('#MAKECALENDARNAME').textbox('getValue');
        $('#BindRelationDialog').dialog({
            title: Calendar,
            width: 950,
            height: 700,
            closed: false,
            cache: false,
            modal: true
        });
        page.InitRelationData();
        page.GetRelationFactoryData();//查询日历--工厂关系
        page.GetRelationResourceData();//查询日历--设备关系
        page.GetRelationWorkcenterData();//查询日历--工区关系
        page.GetRelationTeamData();//查询日历--班组关系
        page.GetRelationEmployeeData();//查询日历--人员关系
    },
    InitRelationData: function () {
        $('#fatory').datagrid({
            columns: [[
                 { field: 'PK', checkbox: true, width: 20, align: 'center' },
                 { field: 'FACTORYNAME', title: '工厂名称', width: 270, align: 'center'}]]
        });
        page.postUrl(getRootPath() + "/Ashx/CommonHandler.ashx", { action: "getFactory" }, function (res) {
            $("#selFactory").combobox({
                    valueField: 'FACTORYID',
                    textField: 'FACTORYNAME',
                    panelHeight: 200,
                    data: res, //下拉数据
                });
        });
        $('#Resource').datagrid({
            onLoadSuccess: function (data) {
                    $('#pp').pagination('refresh', {	// 改变选项，并刷新分页栏信息
                        total: page.pagetotal,
                        pageSize: page.pageSize,
                        pageNumber: page.pageNumber
                    });
                    customizedEasyuiPagination('pp'); //定制化分页
                },
            columns: [[
                { field: 'PK', checkbox: true, width: 20, align: 'center' },
                { field: 'RESOURCENAME', title: '设备编码', width: 100, align: 'center'},
                { field: 'DESCRIPTION', title: '设备名称', width: 170, align: 'center'},
                { field: 'MAKECALENDARNAME', title: '当年日历', width: 170, align: 'center'},
                { field: 'NEXTMAKECALENDARNAME', title: '下年日历', width: 170, align: 'center'}
                ]]
        });
        var formData = { action: "GetMainCaData",MAKEYEAR:Number($('#MAKEYEAR').textbox('getValue'))+1,MAKECALENDARNAME:''};
        page.post(formData, function (res) {
            var data=res.DBTable;
            data.push({MAKECALENDARID:'',MAKECALENDARNAME:'请选择'});
             $("#nextMakeCalendar").combobox({
                    valueField: 'MAKECALENDARID',
                    textField: 'MAKECALENDARNAME',
                    panelHeight: 200,
                    data: res.DBTable, //下拉数据
                    value:''
                });
        });
        //分页事件
            $('#pp').pagination({
                onSelectPage: function (pageNumber, pageSize) {
                    customizedEasyuiPagination('pp'); //定制化分页
                    page.pageSize = pageSize; page.pageNumber = pageNumber;
                    page.GetRelationResourceData();
                }
            });
            //绑定分页go按钮
            $('#pageGo').on("click", function () {
                var pageNumber = $(this).parents('tr').find('.pagination-num').val();
                page.pageNumber = pageNumber;
                page.GetRelationResourceData();
            });
           $('#ResourceCombox').newselectCombox({},{},{url:page.ajaxUrl,action:"getResource",index:0});
//         $('#ResourceCombox').selectCombox({
//            search: function () { },
//            cancel: function () { },
//            selected: function (val, text,record){
//                $('#ResourceID').val(val);
//                $('#txtCombox').textbox('setValue',text);
//                $('#divComboxTxt').show();
//                $('#divComboxSelect').hide();
//                $('#divComboxSearch').show();
//                $('#divComboxClear').hide();
//            }
//        });

         $('#Workcenter').datagrid({
            columns: [[
                 { field: 'PK', checkbox: true, width: 20, align: 'center' },
                 { field: 'WORKCENTERNAME', title: '工区名称', width: 270, align: 'center'}]]
        });
       page.post({ action: "getWorkCenter" }, function (res) {
            $("#WorkcenterID").combobox({
                    valueField: 'WORKCENTERID',
                    textField: 'WORKCENTERNAME',
                    panelHeight: 200,
                    data: res, //下拉数据
                });
        });

         $('#Team').datagrid({
            columns: [[
                 { field: 'PK', checkbox: true, width: 20, align: 'center' },
                 { field: 'TEAMNAME', title: '班组名称', width: 270, align: 'center'}]]
        });
        page.post({ action: "getTeam" }, function (res) {
            $("#TeamID").combobox({
                    valueField: 'TEAMID',
                    textField: 'TEAMNAME',
                    panelHeight: 200,
                    data: res, //下拉数据
                });
        });

        $('#Employee').datagrid({
            onLoadSuccess: function (data) {
                    $('#ppp').pagination('refresh', {	// 改变选项，并刷新分页栏信息
                        total: page.pagetotalp,
                        pageSize: page.pageSizep,
                        pageNumber: page.pageNumberp
                    });
                    customizedEasyuiPagination('ppp'); //定制化分页
                },
            columns: [[
                { field: 'PK', checkbox: true, width: 20, align: 'center' },
                { field: 'EMPLOYEENAME', title: '人员编码', width: 100, align: 'center'},
                { field: 'FULLNAME', title: '人员名称', width: 170, align: 'center'}]]
        });
        //分页事件
            $('#ppp').pagination({
                onSelectPage: function (pageNumber, pageSize) {
                    customizedEasyuiPagination('ppp'); //定制化分页
                    page.pageSize = pageSizep; page.pageNumber = pageNumberp;
                    page.GetRelationEmployeeData();
                }
            });
            //绑定分页go按钮
            $('#ppageGo').on("click", function () {
                var pageNumberp = $(this).parents('tr').find('.pagination-num').val();
                page.pageNumber = pageNumberp;
                page.GetRelationEmployeeData();
            });

             $('#EmployeeCombox').newselectCombox({
              search: function (obj) { },
              cancel: function (obj) { if(obj.index==1){$('#EmployeeID').val('');}else{ $('#ResourceID').val('');}},
              selected: function (val, text,record,obj){
                if(obj.index==1){$('#EmployeeID').val(val);}else{$('#ResourceID').val(val);}
                $('#txtCombox'+obj.index).textbox('setValue',text);
                $('#divComboxTxt'+obj.index).show();
                $('#divComboxSelect'+obj.index).hide(); 
              }
             },{},{url:page.ajaxUrl,action:"GetEmployees",index:1});
             $('#txtCombox0').textbox({prompt:'请输入设备名称'});
             $('#txtCombox1').textbox({prompt:'请输入人员'});
    },
    SaveRelationFactoryData:function(){
        var MID = $('#MAKECALENDARID').val();
        var formData = { action: "SaveRelationFactoryData", MID: MID,FACTORYID:$('#selFactory').combobox('getValue')};
        page.post(formData, function (res) {
            if (res.Result) {
                page.GetRelationFactoryData();
            }
        });
    },
    DaleteRelationFactoryData:function(){
        var FACTORYIDS=[];
        var rows=$('#fatory').datagrid('getChecked');
        $.each(rows,function(index,item){
            FACTORYIDS.push(item.FACTORYID);
        });
        if(FACTORYIDS.length==0){return;}
        var formData = { action: "SaveRelationFactoryData", MID:'',FACTORYID:FACTORYIDS.join(',')};
        page.post(formData, function (res) {
            if (res.Result) {
                page.GetRelationFactoryData();
            }
        });
    },
    GetRelationFactoryData: function () {
        var MID = $('#MAKECALENDARID').val();
        var formData = { action: "GetRelationFactoryData", MID: MID};
        page.post(formData, function (res) {
             $('#fatory').datagrid('loadData',res);
        });
    },
    //-----日历-设备关系-----------------------------------------------------
    SaveRelationResourceData:function(){
        var MID = $('#MAKECALENDARID').val();
        var NEXTMID=$('#nextMakeCalendar').combobox('getValue')
        var formData = { action: "SaveRelationResourceData", MID: MID,NEXTMID:NEXTMID,RESOURCEID: $('#ResourceID').val(),type:'2'};
        page.post(formData, function (res) {
            if (res.Result) {
                page.GetRelationResourceData();
            }
        });
    },
    DaleteRelationResourceData:function(type){
        var RESOURCEIDS=[];
        var rows=$('#Resource').datagrid('getChecked');
        $.each(rows,function(index,item){
            RESOURCEIDS.push(item.RESOURCEID);
        });
        if(RESOURCEIDS.length==0){return;}
        var formData = { action: "SaveRelationResourceData", MID:'',RESOURCEID:RESOURCEIDS.join(','),type:type};
        page.post(formData, function (res) {
            if (res.Result) {
                page.GetRelationResourceData();
            }
        });
    },
    GetRelationResourceData:function(){
        var MID = $('#MAKECALENDARID').val();
        var formData = { 
                action: "GetRelationResourceData", 
                MID: MID,  
                pageSize: page.pageSize,
                pageNumber: page.pageNumber==0?1:page.pageNumber,};
        page.post(formData, function (res) {
             page.pagetotal = res.RowCount;
             $('#Resource').datagrid('loadData',res.DBTable);
        });
    },


    //------------------日历-工区关系-----------------------------------------
    SaveRelationWorkcenterData:function(){
        var MID = $('#MAKECALENDARID').val();
        var formData = { action: "SaveRelationWorkcenterData", MID: MID,WORKCENTERID: $('#WorkcenterID').combobox('getValue')};
        page.post(formData, function (res) {
            if (res.Result) {
                page.GetRelationWorkcenterData();
                page.GetRelationTeamData();
                page.GetRelationEmployeeData();
            }
        });
    },
    DaleteRelationWorkcenterData:function(){
        var WorkcenterIDS=[];
        var rows=$('#Workcenter').datagrid('getChecked');
        $.each(rows,function(index,item){
            WorkcenterIDS.push(item.WORKCENTERID);
        });
        if(WorkcenterIDS.length==0){return;}
        var formData = { action: "SaveRelationWorkcenterData", MID:'',WORKCENTERID:WorkcenterIDS.join(',')};
        page.post(formData, function (res) {
            if (res.Result) {
                page.GetRelationWorkcenterData();
                page.GetRelationTeamData();
                page.GetRelationEmployeeData();
            }
        });
    },
    GetRelationWorkcenterData:function(){
        var MID = $('#MAKECALENDARID').val();
        var formData = { 
                action: "GetRelationWorkcenterData", 
                MID: MID,  
             };
        page.post(formData, function (res) {
             $('#Workcenter').datagrid('loadData',res);
        });
    },
    //-----------------日历-班组关系---------------------------
    SaveRelationTeamData:function(){
        var MID = $('#MAKECALENDARID').val();
        var formData = { action: "SaveRelationTeamData", MID: MID,TEAMID:$('#TeamID').combobox('getValue')};
        page.post(formData, function (res) {
            if (res.Result) {
                page.GetRelationWorkcenterData();
                page.GetRelationTeamData();
                page.GetRelationEmployeeData();
            }
        });
    },
    DaleteRelationTeamData:function(){
        var TEAMIDS=[];
        var rows=$('#Team').datagrid('getChecked');
        $.each(rows,function(index,item){
            TEAMIDS.push(item.TEAMID);
        });
        if(TEAMIDS.length==0){return;}
        var formData = { action: "SaveRelationTeamData", MID:'',TEAMID:TEAMIDS.join(',')};
        page.post(formData, function (res) {
            if (res.Result) {
                page.GetRelationWorkcenterData();
                page.GetRelationTeamData();
                page.GetRelationEmployeeData();
            }
        });
    },
    GetRelationTeamData:function(){
        var MID = $('#MAKECALENDARID').val();
        var formData = { 
                action: "GetRelationTeamData", 
                MID: MID,  
                };
        page.post(formData, function (res) {
             $('#Team').datagrid('loadData',res);
        });
    },
    //-----------------日历-人员关系----------------------------------
    SaveRelationEmployeeData:function(){
        var MID = $('#MAKECALENDARID').val();
        var formData = { action: "SaveRelationEmployeeData", MID: MID,EMPLOYEEID: $('#EmployeeID').val()};
        page.post(formData, function (res) {
            if (res.Result) {
               page.GetRelationWorkcenterData();
                page.GetRelationTeamData();
                page.GetRelationEmployeeData();
            }
        });
    },
    DaleteRelationEmployeeData:function(){
        var EMPLOYEEIDS=[];
        var rows=$('#Employee').datagrid('getChecked');
        $.each(rows,function(index,item){
            EMPLOYEEIDS.push(item.EMPLOYEEID);
        });
        if(EMPLOYEEIDS.length==0){return;}
        var formData = { action: "SaveRelationEmployeeData", MID:'',EMPLOYEEID:EMPLOYEEIDS.join(',')};
        page.post(formData, function (res) {
            if (res.Result) {
                page.GetRelationWorkcenterData();
                page.GetRelationTeamData();
                page.GetRelationEmployeeData();
            }
        });
    },
    GetRelationEmployeeData:function(){
        var MID = $('#MAKECALENDARID').val();
        var formData = { 
                action: "GetRelationEmployeeData", 
                MID: MID,  
                pageSize: page.pageSizep,
                pageNumber: page.pageNumberp==0?1:page.pageNumberp,};
        page.post(formData, function (res) {
             page.pagetotalp = res.RowCount;
             $('#Employee').datagrid('loadData',res.DBTable);
        });
    },


    //清除方法，重要！！！
    reset: function (iscondition, isresult) {
        clearMessage();
    },
    //post数据
    post: function (param, callback) {
        $.ajax({
            type: "Post",
            url: page.ajaxUrl,
            data: param,
            cashe: false,
            async: true,
            dataType: "json",
            beforeSend: function () {
                $.messager.progress({ text: '', msg: '处理中...' });
            },
            success: function (data) {
                $.messager.progress('close');
                callback(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.messager.progress('close');
                displayMessage(XMLHttpRequest.responseText, false);
            }
        });
    },
    postUrl: function (url, param, callback) {
        $.ajax({
            type: "Post",
            url: url,
            data: param,
            cashe: false,
            async: true,
            dataType: "json",
            beforeSend: function () {
                $.messager.progress({ text: '', msg: '处理中...' });
            },
            success: function (data) {
                $.messager.progress('close');
                callback(data);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.messager.progress('close');
                displayMessage(XMLHttpRequest.responseText, false);
            }
        });
    }
}
$(function () {
    page.init();
});